/* 
 * 创建日期 2011-3-31
 *
 * 成都天和软件公司
 * 电话：028-85425861 
 * 传真：028-85425861-8008 
 * 邮编：610041 
 * 地址：成都市武侯区航空路6号丰德万瑞中心B座1001 
 * 版权所有
 */
package  org.fantasy.cpp.core.dao.jdbc;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import  org.fantasy.cpp.core.dao.jdbc.mapper.CommonMapper;
import  org.fantasy.common.db.util.SqlUtil;

/**
 * 功能说明
 * 
 * @author 王文成
 * @version 1.0
 * @since 2011-3-31
 */
public class AbstractDAO<T> {
	
	private static final Log log = LogFactory.getLog(AbstractDAO.class);

	@Autowired
	protected JdbcTemplate jdbcTemplate;
	
	/**
	 * 是否显示SQL
	 */
	protected boolean showSql = true;

	/**
	 * 查询
	 * 
	 * @param sql
	 * @param qryMap
	 * @param type
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected List<T> list(String sql, Map<String, Object> qryMap, Class<T> type) {
		List<Object> paramValues = new ArrayList<Object>();
		String runSql = prepare(sql, paramValues, qryMap);
		Object[] values = paramValues.toArray();
		printRuntimeSql(sql,qryMap);
		return jdbcTemplate.query(runSql, new CommonMapper<T>(type), values);
	}

	/**
	 * 查询
	 * 
	 * @param sql
	 * @param qryMap
	 * @param type
	 * @return
	 */
	protected T get(String sql, Map<String, Object> qryMap, Class<T> type) {
		List<T> list = list(sql, qryMap, type);
		return list.isEmpty() ? null : list.get(0);
	}

	/**
	 * 准备查询
	 * 
	 * @param sql
	 * @param paramValues
	 * @param qryMap
	 * @return
	 */
	protected String prepare(String sql, List<Object> paramValues, Map<String, Object> qryMap) {
		List<String> params = SqlUtil.getParameterList(sql);
		if (!qryMap.isEmpty()) {
			for (String param : params) {
				paramValues.add(qryMap.get(param));
				sql = StringUtils.replaceOnce(sql, ":" + param, "?");
			}
		}
		return sql;
	}
	
	/**
	 * 准备查询
	 * 
	 * @param sql
	 * @param paramValues
	 * @param qryMap
	 * @return
	 */
	protected void printRuntimeSql(String sql, Map<String, Object> qryMap) {
		if( showSql ){
			log.info("\n" + SqlUtil.getRuntimeSql(sql, qryMap));
		}
	}
	
}
